﻿using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using KaytechSoftware.Cms.Entities;
using KaytechSoftware.Cms.Entities.Interfaces;
using KaytechSoftware.Cms.Services.Dto;
using KaytechSoftware.Cms.Services.Interfaces;
using System.Linq;
using KaytechSoftware.Cms.Services.Interfaces.Entity;

namespace KaytechSoftware.Cms.Services.Services.Entity
{
    public class PageService : OrderedEntityBaseService<Page, PageDto>, IPageService
    {
        private readonly IRepository<LeftSideRenderer> _leftSideRendererRepository;
        private readonly IRepository<RightSideRenderer> _rightSideRendererRepository;

        public PageService(IUnitOfWorkService unitOfWorkService, IRepository<Page> pageRepository, IRepository<LeftSideRenderer> leftSideRendererRepository, IRepository<RightSideRenderer> rightSideRendererRepository) : base(unitOfWorkService, pageRepository)
        {
            _leftSideRendererRepository = leftSideRendererRepository;
            _rightSideRendererRepository = rightSideRendererRepository;
        }

        public override void Save(PageDto dto)
        {
            using (var unitOfWork = UnitOfWorkService.Create())
            {
                var page = GetInstance(dto.Id);
                page.Title = dto.Title;
                page.Description = dto.Description;
                page.LeftSideRenderer = _leftSideRendererRepository.GetById(dto.LeftSideRendererId);
                page.RightSideRenderer = _rightSideRendererRepository.GetById(dto.RightSideRendererId);

                Store(page);
                unitOfWork.Commit();
            }
        }

        public override PageDto GetDtoById(long id)
        {
            using (UnitOfWorkService.Create())
            {
                var entity = EntityRepository.GetAll(new Expression<Func<Page, object>>[] { p => p.LeftSideRenderer, p => p.RightSideRenderer }).FirstOrDefault(p => p.Id == id);
                return new PageDto(entity);
            }
        }

        public override IList<PageDto> GetAll()
        {
            using (UnitOfWorkService.Create())
            {
                var pages = EntityRepository.GetAll(new Expression<Func<Page, object>>[] { p => p.LeftSideRenderer, p => p.RightSideRenderer }).OrderByDescending(p => p.Order).ToList();
                return pages.Select(p => new PageDto(p)).ToList();
            }
        }
    }
}
